<?php

namespace app\controller;
use app\model\Friends;
use app\validate\User as UserValidate;
use app\model\User as UserModel;
use app\model\Authors as AuthorModel;
use think\api\Client;
use think\exception\ErrorException;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Session;
use think\facade\Validate;
use think\Request;
use think\route\Rule;
use phpmailer\PHPMailer;
use phpmailer\SMTP;
use phpmailer\Exception;
class User extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(){
        $username=Session::get('username');
        $user=UserModel::where('userName',$username)->find()->toArray();
        return $this->createApi($user,'success',200);
    }

    /**
     * 显示创建资源表单页.
     *@param  \think\Request  $request
     * @return \think\Response
     */
    public function create(Request $request)
    {
        $data=$request->param();
        try {
            if($data['username']!=null&&$data['password']!=null&&$data['email']!=null){
                $username=$data['username'];
                validate(UserValidate::class)
//                ->batch(true)
                    ->check($data);
                $user=UserModel::where('userEmail',$data['email'])
                    ->whereOr('userName',$data['username'])
                    ->field('userId')->find();
                //把email作为存在依据
                if(!$user->isEmpty()) {
                    return $this->createApi([], '用户名或用户邮箱已存在', 204);
                }
                $user=UserModel::create([
                    'userName'=>$data['username'],
                    'userPassword'=>md5($data['password']),
                    'userEmail'=>$data['email']
                ])->toArray();

                if ($user) {
                    Session::set('username',$username);
                    return $this->createApi($user, '注册成功', 200);
                } else {
                    return $this->createApi([], '注册失败', 204);
                }
            }else{
                return $this->createApi([],'必填项未填',400);
            }
        } catch (ValidateException $exception) {
            return $this->createApi([], $exception->getError(), 400);
        }
    }
    public function miss(){
        $user=UserModel::where('userEmail','20191103283@gdufs.edu.cn')->select()->toArray();
        $result=[];$i=0;
        foreach ($user as $arr){
            $s='data'.$i;
            $result[$s]=$arr;
            $i++;
        }
        return $this->createApi($result[0],'必填项未填',400);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save()
    {
        if(!cookie('PHPSESSID')){
            return $this->createApi([],'未登录',400);
        }else{
            Session_id(cookie('PHPSESSID'));
            return Session::get('username');
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function read(Request $request)
    {

        $data=$request->param();
        $username=addslashes(strip_tags($data['username']));
        $password=addslashes(strip_tags($data['password']));
        $user=UserModel::where('userName','like',$username)
            ->where('userPassword','=',md5($password))
            ->find();
        if($user){
            $user=$user->toArray();
            $session_id=Session_id();
            Session::set('user_id',$user['userId']);
            Session::set('username',$username);
            cookie('PHPSESSID',$session_id,3600);
            return $this->createApi($user,'登录成功',200);
        }else{
            return $this->createApi([], '登录失败', 204);
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     *
     * @return \think\Response
     */
    public function update(Request $request)
    {

            $username=Session::get('username');
            $data=$request->param();
            try {
                validate(UserValidate::class)
                    ->scene('update')
                    ->check($data);
            } catch (ValidateException $exception) {
                return $this->createApi([], $exception->getError(), 400);
            }
            $sex="";
            if($data['sex']==1){
                $sex="女";
            }else{
                $sex="男";
            }
            if($username){
                $user = UserModel::where('userName', $username)
                    ->update(['userSex' => $sex,'userStatement'=>$data['statement']]);
                $userData=Db::name('user')->where('userName', $username)->find();
                if (empty($user)) {
                    return $this->createApi([], '修改失败', 204);
                } else {
                    return $this->createApi($user, '修改成功', 200);
                }
            }


    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function logout()
    {
        Session::delete('username');
        if(Session::get('username')==null){
            return $this->createApi([], '登出成功', 200);
        }
    }
    public function upload(){
        $username=Session::get('username');
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        if(!empty($file)){
            try {
                validate(UserValidate::class)
                    ->scene('upload')
                    ->check((array)$file);
                if($username){
                    $user=UserModel::where('userName',$username)->find();
                    $array=$user->toArray();
                    if(!empty($array['userImage'])&&$array['userImage']!='storage/user/true.jpg'){
                        unlink('../public/'.$array['userImage']);
                    }
                    $savename = \think\facade\Filesystem::disk('public')->putFile( 'user', $file);
                    $savename='storage/'.str_replace('\\','/',$savename);
                    $user->userImage=$savename;

                    $friend=Friends::where('friend_name',$username)->select();
                    if($friend){
                        foreach ($friend as $a){

                        }
                    }
                    if($user->save()){
                        return $this->createApi('storage/'.str_replace('\\','/',$savename), '上传成功', 200);
                    }else{
                        return $this->createApi([], '上传失败', 204);
                    }
                }else{
                    return $this->createApi([], '登录过期', 204);
                }
            } catch (ValidateException $e) {
                return $this->createApi([], $e->getError(), 400);
            }
        }

        // 上传到本地服务器

    }
    public function mail($toemail,$code,$time){
//        $toemail = '20191103283@gdufs.edu.cn';//定义收件人的邮箱

        $mail = new PHPMailer;

        $mail->isSMTP();// 使用SMTP服务
        $mail->CharSet = "utf8";// 编码格式为utf8，不设置编码的话，中文会出现乱码
        $mail->Host = "smtp.163.com";// 发送方的SMTP服务器地址
        $mail->SMTPAuth = true;// 是否使用身份验证
        $mail->Username = "a261547032a@163.com";// 发送方的163邮箱用户名，就是你申请163的SMTP服务使用的163邮箱</span><span style="color:#333333;">
        $mail->Password = "WZGZKYNRPJMZXOMJ";// 发送方的邮箱密码，注意用163邮箱这里填写的是“客户端授权密码”而不是邮箱的登录密码！</span><span style="color:#333333;">
//            $mail->SMTPSecure = "ssl";// 使用ssl协议方式</span><span style="color:#333333;">
        $mail->Port = 25;// 163邮箱的ssl协议方式端口号是465/994

        $mail->setFrom("a261547032a@163.com","Mailer");// 设置发件人信息，如邮件格式说明中的发件人，这里会显示为Mailer(xxxx@163.com），Mailer是当做名字显示
        $mail->addAddress($toemail);// 设置收件人信息，如邮件格式说明中的收件人，这里会显示为Liang(yyyy@163.com)
        $mail->addReplyTo("a261547032a@163.com","Reply");// 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址
        //$mail->addCC("xxx@163.com");// 设置邮件抄送人，可以只写地址，上述的设置也可以只写地址(这个人也能收到邮件)
        //$mail->addBCC("xxx@163.com");// 设置秘密抄送人(这个人也能收到邮件)
        //$mail->addAttachment("bug0.jpg");// 添加附件


        $mail->Subject = "验证邮箱";// 邮件标题
        $mail->Body  = $time."用户，您好：<br/>这是您的验证码:
    <br/>" . $code . "</a>";// 邮件正文
        //$mail->AltBody = "This is the plain text纯文本";// 这个是设置纯文本方式显示的正文内容，如果不支持Html方式，就会用到这个，基本无用
        $mail->isHTML();
        if(!$mail->send()){// 发送邮件
//			    echo "Message could not be sent.";
//                echo "Mailer Error: ".$mail->ErrorInfo;// 输出错误信息
            return false;

        }else{
//                echo '发送成功';
            return true;
        }
    }

    public function passwordMail($toemail,$url,$time){
//        $toemail = '20191103283@gdufs.edu.cn';//定义收件人的邮箱

        $mail = new PHPMailer;

        $mail->isSMTP();// 使用SMTP服务
        $mail->CharSet = "utf8";// 编码格式为utf8，不设置编码的话，中文会出现乱码
        $mail->Host = "smtp.163.com";// 发送方的SMTP服务器地址
        $mail->SMTPAuth = true;// 是否使用身份验证
        $mail->Username = "a261547032a@163.com";// 发送方的163邮箱用户名，就是你申请163的SMTP服务使用的163邮箱</span><span style="color:#333333;">
        $mail->Password = "WZGZKYNRPJMZXOMJ";// 发送方的邮箱密码，注意用163邮箱这里填写的是“客户端授权密码”而不是邮箱的登录密码！</span><span style="color:#333333;">
//            $mail->SMTPSecure = "ssl";// 使用ssl协议方式</span><span style="color:#333333;">
        $mail->Port = 25;// 163邮箱的ssl协议方式端口号是465/994

        $mail->setFrom("a261547032a@163.com","Mailer");// 设置发件人信息，如邮件格式说明中的发件人，这里会显示为Mailer(xxxx@163.com），Mailer是当做名字显示
        $mail->addAddress($toemail);// 设置收件人信息，如邮件格式说明中的收件人，这里会显示为Liang(yyyy@163.com)
        $mail->addReplyTo("a261547032a@163.com","Reply");// 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址
        //$mail->addCC("xxx@163.com");// 设置邮件抄送人，可以只写地址，上述的设置也可以只写地址(这个人也能收到邮件)
        //$mail->addBCC("xxx@163.com");// 设置秘密抄送人(这个人也能收到邮件)
        //$mail->addAttachment("bug0.jpg");// 添加附件
        $mail->isHTML();

        $mail->Subject = "找回密码";// 邮件标题
        $mail->Body = "用户，您好：<br/>您在".$time."提交了找回密码请求。请点击下面的链接重置密码
//    （按钮24小时内有效）。<br/><a href='".$url."'target='_blank'>".$url."</a>";// 邮件正文
        //$mail->AltBody = "This is the plain text纯文本";// 这个是设置纯文本方式显示的正文内容，如果不支持Html方式，就会用到这个，基本无用

        if(!$mail->send()){// 发送邮件
//			    echo "Message could not be sent.";
//                echo "Mailer Error: ".$mail->ErrorInfo;// 输出错误信息
            return false;

        }else{
//                echo '发送成功';
            return true;
        }
    }

    public function reset(Request $request){
        $data=$request->param();
        $email=stripcslashes(trim($data['email']));
        $token=stripcslashes(trim($data['token']));
        $user=UserModel::where('userEmail',$email)->find()->toArray();
        $temp = md5($user['userId'].$user['userName'].$user['userPassword']);
        if($temp==$token){
            return redirect('http://121.4.214.174/quantawork/code/forgetPassword/forgetPassword.html?email='.$email);
        }else{
            return redirect('http://121.4.214.174/404.html');
        }
    }

    public function processReset(Request $request){
        $data=$request->param();
        $email=$data['email'];
        $user=UserModel::where('userEmail',$email)->find();
        try {
            validate(UserValidate::class)
                ->scene('passwordForget')
                ->check($data);
            $user->userPassword=md5($data['password']);
            if($user->save()){
                return $this->createApi($user, 'reset successfully', 200);
            }
        } catch (ValidateException $e) {
            return $this->createApi([], $e->getError(), 400);
        }
    }

    public function forgetPassword(Request $request){
        $data=$request->param();
        $username=$data['username'];
        $email=$data['email'];
        $user=UserModel::where('userName',$username)->find()->toArray();
        $email= stripslashes(trim($email));
        $uid=$user['userId'];
        $token=md5($uid.$username.$user['userPassword']);
        $url='http://121.4.214.174/user/reset?email='.$email.'&token='.$token;
        $sendtime = date('Y-m-d H:i:s',time());
        $result=$this->passwordMail($email,$url,$sendtime);
        if($result){
            return $this->createApi([],'系统已向您的邮箱发送了一封邮件,请登录到您的邮箱及时重置您的密码！',200);
        }else{
            return $this->createApi([],'failed',204);
        }
    }

    public function schoolMail(Request $request){
        $username=Session::get('username');
        $user=UserModel::where('userName',$username)->find();
        $data=$request->param();
        if($data['school_email']==null){
            return $this->createApi([],'failure',204);
        }
        $user->school_email=$data['school_email'];
        $user->save();
        if(preg_match('/^([a-z0-9]+)*@(.*)\.edu(.*)/',$user->school_email,$b)){
            if(preg_match('/^([0-9]{4})(.*)$/i',$user->school_email,$a)){
                $user->userSchool=$b[2].$a[1];
                $user->save();
            }
        }else{
            return $this->createApi([],'school failure',204);
        }
        $getpasstime = time();
        Session::set('getpasstime',$getpasstime);
        $code = "";
        $arr = array();//设置验证码
        for ($i = 0; $i < 4; $i++) {
            $arr[$i] = rand(0, 9);
            $code.= (string)$arr[$i];
        }//设置入session中，方便比对
        Session::set("validcode",$code);
        $resettime = time();
        $sendtime = date('Y-m-d H:i:s', time());
        if($this->mail($user->school_email, $code, $sendtime)){
            return $this->createApi([],'发送成功',200);
        }else{
            return $this->createApi([],'发送失败',204);
        }
    }
    public function schoolConfirm(Request $request){
        $data=$request->param();
        $username=Session::get('username');
        $user=UserModel::where('userName',$username)->find();
        if(isset($data['validate'])){
            $yanzheng=$data['validate'];
            if($yanzheng==Session::get('validcode')){
                if(time()-Session::get('getpasstime')>24*60*60){
                    return $this->createApi([],'已过期',204);
                }else{
                    $user->is_confirm=1;
                    $user->save();
                    return $this->createApi([],'验证成功',200);
                }
            }else{
                return $this->createApi([],'验证码错误',204);
            }
        }
    }
    function getRealIp(){
        $ip=FALSE;
        //客户端IP 或 NONE
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
            for ($i = 0; $i < count($ips); $i++) {
                if (!mb_ereg_match("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        //客户端IP 或 (最后一个)代理服务器 IP
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }
    public function ipCheck(){
        $client = new Client("e747eb93872e232eb191c399c5ccf49a");
        $result = $client->ipIndex()
            ->withIp('192.168.18.1')
            ->request();
        dump($result);
    }
    public function friend(Request $request){
        $data=$request->param();
        $username=Session::get('username');
        $user1=UserModel::where('userName',$username)->find();
        $user2=UserModel::where('userId',$data['id'])->find();
        $friend=Friends::where('username',$username)->where('friend_id',$data['id'])->find();
        if($friend){
            return $this->createApi([],'the friend has existed',204);
        }
        $friend=Friends::create([
            'user_id'=>$user1->userId,
            'user_name'=>$username,
            'user_head'=>$user1->userImage,
            'friend_id'=>$data['id'],
            'friend_name'=>$user2->userName,
            'friend_head'=>$user2->userImage
        ])->toArray();
        return $this->createApi($friend, 'success', 200);
    }
    public function search(Request $request){
        $data=$request->param();
        $users=UserModel::where('userName','like','%'.$data['name'].'%')
            ->select();
        return $this->createApi($users, 'success', 200);
    }
    public function friendList(){
        $username=Session::get('username');
        $friends=Friends::where('user_name',$username)->select();
        if($friends){
            for($i=0;$i<sizeof($friends);$i++){
                $friends[$i]->friend_head=$friends[$i]->profile->userImage;
            }
        }
        return $this->createApi($friends, 'success', 200);
    }
    public function test(){
        if(preg_match('/^([a-z0-9]+)*@(.*)\.edu(.*)/',"20191103283@gdufs.edu.cn",$b)){
            if(preg_match('/^([0-9]{4})(.*)$/i',"20191103283@gdufs.edu.cn",$a)){
                $result=[];
                $result[]=$a[1];
                $result[]=$b[2];
                return $this->createApi($result, 'success', 200);
            }
        }
    }

}
